/**
 *
 *
 */
(function( $scope ) {

    function elem( elem, builder ){
        if( elem.constructor === String ){
            builder.push( elem );
        } else if( elem.constructor === Array ) {
            arrayElem( elem,builder );
        } else {
            throw new Error('Improper node type');
        }
    }

    function arrayElem( elem, builder ){
        var hasAttrs, e0, t;
        if( !elem.length ){
            return '';
        }
        e0 = elem[0].constructor;
        // if [[],[]]
        if( e0 === Array ){
            childs( elem, 0, builder );
        // if ['.some']
        } else if( e0 === String ) {
            hasAttrs = elem[1] && elem[1].constructor === Object;
            t = tag(elem[0], hasAttrs ? elem[1] : null );
            builder.push(t[0]);
            childs( elem, hasAttrs ? 2 : 1, builder );
            builder.push(t[1]);
        } else {
            throw new Error("Improper tag type[" + e0 + "]");
        }
    }

    function childs( array, startFrom, builder ){
        for( var i = startFrom, len = array.length;i < len; i++ ){
            elem(array[i], builder);
        }
    }

    function tag( type, attrs ){
        var tm = type.match(/^%([^\.#]*)/), tg = tm && tm[1] ? tm[1] : 'div',
            cm = type.match(/\.([\.a-zA-Z_\-0-9]*)/), cls = cm && cm[1] ? cm[1] : null,
            idm = type.match(/#([a-zA-Z_\-0-9]*)/), id = idm && idm[1] ? idm[1] : null,
            attrstr = '', attrvalue;
        if( attrs ){
            for( var k in attrs ){
                attrvalue = attrs[k].constructor === String ?
                    '"' + attrs[k] + '"' : attrs[k];
                attrstr += k + '=' + attrvalue + ' ';
            }
            attrstr.length && (attrstr = attrstr.substr(0, attrstr.length - 1));
        }
        return [
            '<' + tg +
                ( id ? ' id="' + id + '"' : '') +
                ( cls ? ' class="' + cls.replace(/\./ig,' ') + '"' : '') +
                ( attrstr.length ? ' ' + attrstr : '' )+ ">",
            '</' + tg + '>'
        ];
    }

    $scope.Haml = {
        toHtml: function( tpl ){
            var sb = [];
            elem(tpl, sb);
            return sb.join('');
        }
    };

})( window );


